/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.raflik.queryxml.ui.model;

import java.util.Collections;
import java.util.List;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.w3c.dom.NodeList;
import pl.raflik.queryxml.langservice.ConvUtil;

/**
 *
 * @author raflik
 */
public class ResultChildren extends Children.Keys<Object> {

    private Object node;

    public static Children createChildren(Object node) {
        if (node instanceof List) {
            List<?> list = (List<?>) node;
            if (list.size() > 0) {
                return new ResultChildren(node);
            }
        }
        if (node instanceof org.w3c.dom.Node) {
            org.w3c.dom.Node xmlNode = (org.w3c.dom.Node) node;
            NodeList children = xmlNode.getChildNodes();
            if (children.getLength() > 0) {
                return new ResultChildren(node);
            }
        }
        return Children.LEAF;
    }

    private ResultChildren(Object node) {
        this.node = node;
    }

    @Override
    protected void addNotify() {
        List<?> list = null;
        if (node instanceof org.w3c.dom.Node) {
            org.w3c.dom.Node xmlNode = (org.w3c.dom.Node) node;
            NodeList children = xmlNode.getChildNodes();
            list = ConvUtil.toList(children);
        } else if (node instanceof List) {
            list = (List<?>) node;
        } else {
            list = Collections.singletonList(node);
        }
        if (list.size() > 0) {
            setKeys(list);
        }
    }

    @Override
    protected Node[] createNodes(Object obj) {
        return new Node[]{new ResultNode(obj)};
    }
}
